var vm = new Vue({
    el: '#app',
    data: {
        HOST,
        title: '',
        label: '',
        content: '',
        error_title: false,
        error_label: false,
        error_content: false,
        username: sessionStorage.username || localStorage.username,
        user_id: sessionStorage.user_id || localStorage.user_id,
        token: sessionStorage.token || localStorage.token,
    },
    // mounted: function () {
    //     axios.get(this.host + 'question/', {responseType: 'json'})
    //         .then(response => {
    //             this.questions = response.data;
    //         })
    //         .catch(response => {
    //             console.log(error.response.data)
    //         })
    // },
    methods: {
        // 获取url路径参数
        get_query_string: function (name) {
            var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
            var r = window.location.search.substr(1).match(reg);
            if (r != null) {
                return decodeURI(r[2]);
            }
            return null;
        },
        // 检查数据
        check_title: function () {
            if (!this.title) {
                this.error_title = true;
            } else {
                this.error_title = false;
            }
        },
        check_label: function () {
            if (!this.title) {
                this.error_label = true;
            } else {
                this.error_label = false;
            }
        },
        check_content: function () {
            if (!this.title) {
                this.error_content = true;
            } else {
                this.error_content = false;
            }
        },
        // 表单提交
        on_submit: function () {
            this.check_title();
            this.check_label();
            this.check_content();

            if (this.error_title == false && this.error_label == false && this.error_content == false) {
                axios.post(this.HOST + '/question/', {
                        author:this.user_id,
                        title: this.title,
                        label: this.label,
                        content: CKEDITOR.instances.editor1.getData(),
                    },
                    {
                        headers:{
                            'Authorization':'JWT '+this.token
                        }
                    },
                    {
                        responseType: 'json',
                    })
                    .then(response => {

                        // 跳转页面
                        var return_url = this.get_query_string('next');
                        if (!return_url) {
                            return_url = '/qa-logined.html';
                        }
                        location.href = return_url;
                    })
                    .catch(error => {
                        console.log(error.response.data)
                    })
            }
        },
    }
});
